package com.crois.barrier.admin.healthcheck;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crois.barrier.admin.entity.BarrierServer;
import com.crois.barrier.admin.server.ServerListManager;
import com.crois.barrier.common.constants.Constants;
import com.crois.barrier.common.executor.GlobalExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2020/10/23
 */
@Component("serverClusterHealthCheck")
public class ServerClusterHealthCheck {

    private Logger LOGGER = LoggerFactory.getLogger(ServerClusterHealthCheck.class);

    @Autowired
    private ServerListManager serverListManager;


    @PostConstruct
    public void init(){
        GlobalExecutor.registerServerHealthCheck(new ServerHealthCheck());
    }


    public class ServerHealthCheck implements Runnable {
        @Override
        public void run() {
            List<BarrierServer> serverList = serverListManager.getServerList();
            if (CollectionUtils.isNotEmpty(serverList)){
                for (BarrierServer server : serverList) {
                    LOGGER.info("【server health check】,ip:{},port:{},lastBeat:{}",server.getIp(),server.getPort(),server.getLastBeat());
                    if (System.currentTimeMillis()-server.getLastBeat()> Constants.DEFAULT_BARRIER_HEART_BEAT_TIMEOUT){
                        LOGGER.info("server ip:{},port:{}, msg: server timeout after {}, last beat: {}",
                                server.getIp(), server.getPort(),
                                Constants.DEFAULT_BARRIER_HEART_BEAT_TIMEOUT, server.getLastBeat());
                        // 设置 服务 为 不健康 和 不可用
                        server.setHealthy(false);
                    }
                    if (System.currentTimeMillis()-server.getLastBeat()> Constants.DEFAULT_BARRIER_IP_DELETE_TIMEOUT){
                        // 删除 服务
                        LOGGER.info("server ip:{},port:{}, msg: server timeout after {}, last beat: {}",
                                server.getIp(), server.getPort(),
                                Constants.DEFAULT_BARRIER_IP_DELETE_TIMEOUT, server.getLastBeat());
                        server.setEnabled(false);
                    }
                }
            }
        }
    }
}
